package com.bstek.urule.console.servlet.permission;

import com.bstek.urule.RuleException;
import com.bstek.urule.console.servlet.base.BaseController;
import com.bstek.urule.console.EnvironmentUtils;
import com.bstek.urule.console.User;
import com.bstek.urule.console.repository.RepositoryService;
import com.bstek.urule.console.repository.RepositoryServiceImpl;
import com.bstek.urule.console.repository.model.RepositoryFile;
import com.bstek.urule.console.repository.permission.PermissionStore;
import com.bstek.urule.console.servlet.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author zhouchaoliang
 * @since 2021/12/9
 */
@Controller
public class PermissionConfigController extends BaseController {
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private PermissionStore permissionStore;

    @GetMapping("/urule/permission")
    public ModelAndView permission(HttpServletRequest req, HttpServletResponse resp) {
        ModelAndView mv = new ModelAndView("/permission-config-editor");
        mv.addObject("contextPath", req.getContextPath());
        return mv;
    }

    @ResponseBody
    @GetMapping("/urule/permission/loadResourceSecurityConfigs")
    public List<UserPermission> loadResourceSecurityConfigs(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String companyId = EnvironmentUtils.getLoginUser(new RequestContext(req, resp)).getCompanyId();
        try {
            List<UserPermission> permissions = repositoryService.loadResourceSecurityConfigs(companyId);
            List<User> users = EnvironmentUtils.getEnvironmentProvider().getUsers();
            if (users == null) users = new ArrayList<User>();
            List<UserPermission> result = new ArrayList<UserPermission>();
            for (User user : users) {
                if (user.isAdmin()) {
                    continue;
                }
                if (companyId != null) {
                    if (user.getCompanyId() == null) {
                        continue;
                    }
                    if (!user.getCompanyId().equals(companyId)) {
                        continue;
                    }
                }
                boolean exist = false;
                for (UserPermission p : permissions) {
                    if (p.getUsername().equals(user.getUsername())) {
                        exist = true;
                        break;
                    }
                }
                if (exist) {
                    continue;
                }
                UserPermission up = new UserPermission();
                up.setProjectConfigs(new ArrayList<ProjectConfig>());
                up.setUsername(user.getUsername());
                result.add(up);
            }
            result.addAll(permissions);
            List<RepositoryFile> projects = repositoryService.loadProjects(companyId);
            for (UserPermission p : result) {
                buildProjectConfigs(projects, p);
            }
            return result;
        } catch (Exception ex) {
            throw new RuleException(ex);
        }
    }

    @PostMapping("/urule/permission/saveResourceSecurityConfigs")
    public void saveResourceSecurityConfigs(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = EnvironmentUtils.getLoginUser(new RequestContext(req, resp));
        String companyId = user.getCompanyId();
        String content = req.getParameter("content");
        String path = RepositoryServiceImpl.RESOURCE_SECURITY_CONFIG_FILE + (companyId == null ? "" : companyId);
        try {
            repositoryService.saveFile(path, content, false, null, user);
            permissionStore.refreshPermissionStore();
        } catch (Exception ex) {
            throw new RuleException(ex);
        }
    }

    private void buildProjectConfigs(List<RepositoryFile> projects, UserPermission p) {
        List<ProjectConfig> configs = p.getProjectConfigs();
        if (configs == null) {
            configs = new ArrayList<ProjectConfig>();
            p.setProjectConfigs(configs);
        }
        for (RepositoryFile project : projects) {
            boolean exist = false;
            for (ProjectConfig c : p.getProjectConfigs()) {
                if (project.getName().equals(c.getProject())) {
                    exist = true;
                    break;
                }
            }
            if (exist) {
                continue;
            }
            ProjectConfig config = new ProjectConfig();
            config.setProject(project.getName());
            configs.add(config);
        }
    }
}
